package org.superheroes.androidserver.net.server.discovery;

import java.net.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.io.*;

import org.apache.http.conn.util.InetAddressUtils;

public class DiscoveryHandler
{

	private final String		dbServerIpAddress	= "10.87.129.40";

	private InetAddress			localInetAddress;
	private String				localHostAddress;
	private String				localHostName;

	private File				folder;
	private File[]				listofFiles;
	private ArrayList<String>	fileNames;							// ?

	public DiscoveryHandler()
	{

		try
		{
			getNetworkInfo();
		}
		catch ( UnknownHostException netE )
		{
			netE.printStackTrace();
		}

		getFiles();

		try
		{
			insertAvailable( getIPAddress( true ), fileNames );
		}
		catch ( IOException dbE )
		{
			dbE.printStackTrace();
		}

	}

	private void getNetworkInfo() throws UnknownHostException
	{

		localInetAddress = InetAddress.getLocalHost();
		localHostAddress = localInetAddress.getHostAddress();

		// Android emulator sets 127.0.0.1/localhost ...
		if ( localInetAddress.toString() == "localhost/127.0.0.1" )
		{
			localInetAddress = InetAddress.getByName( "10.87.129.40" );
			localHostAddress = localInetAddress.getHostAddress();
		}

		localHostName = localInetAddress.getHostName();
	}

	private void getFiles()
	{
		folder = new File( "/data/movies" );
		listofFiles = folder.listFiles();
		fileNames = new ArrayList<String>();

		for ( int i = 0; i < listofFiles.length; i++ )
		{
			if ( listofFiles[ i ].isFile() )
			{
				fileNames.add( listofFiles[ i ].getName() );
			}
		}

	}

	private void insertAvailable( String machine, ArrayList<String> files ) throws IOException
	{
		URL url = new URL( "http://" + dbServerIpAddress + "/websites/mm_discovery/discovery_insert.php" );
		HttpURLConnection connection = ( HttpURLConnection ) url.openConnection();
		String result = "";

		StringBuilder sb = new StringBuilder();
		sb.append( "status=" );

		sb.append( machine );
		sb.append( "," );

		for ( String s : fileNames )
		{
			sb.append( s );
			sb.append( "," );
		}

		String data = removeLastChar( sb.toString() );

		try
		{
			connection.setDoInput( true );
			connection.setDoOutput( true );
			connection.setUseCaches( false );
			connection.setRequestMethod( "POST" );
			connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" );

			// Do POST
			DataOutputStream dataOut = new DataOutputStream( connection.getOutputStream() );
			dataOut.writeBytes( data );
			dataOut.flush();
			dataOut.close();

			// Read result
			BufferedReader in = null;
			try
			{
				String line;
				in = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );
				while ( ( line = in.readLine() ) != null )
				{
					result += line;
				}
			}
			finally
			{
				if ( in != null )
				{
					in.close();
				}
			}

		}
		finally
		{
			connection.disconnect();
			System.out.println( result );
		}

	}

	public String removeLastChar( String s )
	{
		if ( s == null || s.length() == 0 )
		{
			return s;
		}
		return s.substring( 0, s.length() - 1 );
	}

	public static String getIPAddress( boolean useIPv4 )
	{
		try
		{
			List<NetworkInterface> interfaces = Collections.list( NetworkInterface.getNetworkInterfaces() );
			for ( NetworkInterface intf : interfaces )
			{
				List<InetAddress> addrs = Collections.list( intf.getInetAddresses() );
				for ( InetAddress addr : addrs )
				{
					if ( ! addr.isLoopbackAddress() )
					{
						String sAddr = addr.getHostAddress().toUpperCase();
						boolean isIPv4 = InetAddressUtils.isIPv4Address( sAddr );
						if ( useIPv4 )
						{
							if ( isIPv4 )
								return sAddr;
						}
						else
						{
							if ( ! isIPv4 )
							{
								int delim = sAddr.indexOf( '%' ); // drop ip6
																	// port
																	// suffix
								return delim < 0 ? sAddr : sAddr.substring( 0, delim );
							}
						}
					}
				}
			}
		}
		catch ( Exception ex )
		{
		} // for now eat exceptions
		return "";
	}

}
